<template>
  <div class="q-pa-md bg-white">
    <q-table flat separator="none" :rows="dataList" :columns="columns" no-data-label="暂无数据"
      no-results-label="过滤器没有发现任何结果" row-key="name" :visible-columns="visibleColumns" v-model:pagination="pagination"
      hide-pagination>
      <!-- 表格的加载状态 -->
      <template v-slot:loading>
        <q-inner-loading showing color="grey" />
      </template>
      <!-- 表格顶部 -->
      <template v-slot:top v-if="searchShow">
        <div style="width: 200px" class="q-mt-xs q-mr-sm">
          <q-select dense outlined options-dense v-model="headerSeach" :options="selectSeach" />
        </div>
        <div v-show="headerSeach" style="width: 200px" class="q-mr-sm q-mt-xs">
          <q-input outlined v-model="queryList[seachContent[headerSeach]]" dense />
        </div>
        <q-btn class="q-mr-sm q-mt-xs borderRadius" unelevated padding="8px 8px 7px" icon="search" color="primary"
          label="搜索" @click="handlerSearch" />
        <q-btn class="q-mr-sm q-mt-xs borderRadius" unelevated padding="8px 8px 7px" color="primary" label="复位搜索"
          @click="handleResetSearch" />
        <q-btn class="q-mr-sm q-mt-xs borderRadius" unelevated padding="8px 8px 7px" icon="add_circle_outline"
          color="primary" @click="handlerAddSensor" label="添加" />
        <q-space />
        <q-select v-model="visibleColumns" multiple outlined dense options-dense :display-value="'表头选择'" emit-value
          map-options :options="columns" option-value="name" options-cover style="min-width: 150px"
          class="q-mr-sm q-mt-xs" />
      </template>
      <!-- 无数据提示信息 -->
      <template v-slot:no-data="{ message }">
        <div class="full-width row flex-center text-accent q-gutter-sm">
          <span>{{ message }}</span>
        </div>
      </template>
      <!-- 表格头部 -->
      <template v-slot:header="props">
        <q-tr :props="props"
          :class="themeColor.primary == '#FF9F03' ? 'headTr' : `${themeColor.primary == '#004288' ? 'headTrTwo' : 'headTrThree'}`">
          <q-th v-for="col in props.cols" :key="col.name" :props="props">
            {{ col.label }}
            <q-icon v-if="col.isSort" class="cursor-pointer" size="18px"
              :name="pagination.descending ? 'expand_less' : 'expand_more'" @click="handlerSort"></q-icon>
          </q-th>
          <q-th width="140px">操作</q-th>
        </q-tr>
      </template>
      <!-- 表格主体 -->
      <template v-slot:body="props">
        <q-tr no-hover :props="props" class="tableTr">
          <q-td v-for="col in props.cols" :key="col.name" :props="props">
            <span>{{ col.value }}</span>
          </q-td>
          <q-td width="160px">
            <EditBtn :btnTitle="'重置密码'" @click="handleModify(props.row)" />
            <EditBtn @click="handlerEbitSensor(props.row)" />
            <DeleteBtn @click="handlerDeleteSensor(props.row)" />
          </q-td>
        </q-tr>
      </template>
    </q-table>
    <!-- 分页 -->
    <Pagination :pageSizes="['10条/页', '20条/页', '30条/页', '50条/页']" @updatePage="updatePage" @updateSizes="updateSizes"
      :pagination="pagination" @handlerRefresh="handlerRefresh" />
  </div>

  <q-dialog v-model="isAddOrUpdate" persistent @mousedown="dialogDrag($event, 1)" @mousemove="dragIcon($event)">
    <q-card>
      <!-- 对话框的头部 -->
      <q-card-section class="row items-center q-pb-none">
        <div class="text-h6">{{ textMap[dialogStatus] }}</div>
        <q-space />
        <q-btn icon="close" flat round dense @click="closeEbitUpdate"></q-btn>
      </q-card-section>
      <!-- 对话框的主体-->
      <q-card-section class="q-pt-none">
        <q-form ref="dataForm" class="q-pa-lg dialog-form-container">
          <ul>
            <li>
              <div>
                <span style="color: red">*</span>
                用户名
              </div>
              <div>
                <q-input outlined v-model="creatUpdateQuery.username" dense :rules="rulesArr[0]" />
              </div>
            </li>
            <li>
              <div>
                <span style="color: red">*</span>
                电话
              </div>
              <div>
                <q-input outlined v-model="creatUpdateQuery.telephone" dense :rules="rulesArr[1]" />
              </div>
            </li>
            <li class="gap_wrepper">
              <div>邮箱</div>
              <div>
                <q-input outlined v-model="creatUpdateQuery.email" dense />
              </div>
            </li>
            <li v-show="dialogStatus === 'create'">
              <div>
                <span style="color: red">*</span>
                密码
              </div>
              <div>
                <q-input dense outlined :type="loginPass" lazy-rules placeholder="密码"
                  v-model="creatUpdateQuery.password" standout bg-color="white" bottom-slots :rules="rulesArr[2]">
                  <template v-slot:append>
                    <q-icon :name="isPwd ? 'visibility_off' : 'visibility'" class="cursor-pointer" @click="showPwd" />
                  </template>
                </q-input>
              </div>
            </li>
            <li v-show="dialogStatus === 'create'">
              <div>
                <span style="color: red">*</span>
                确认密码
              </div>
              <div>
                <q-input dense outlined :type="loginPass2" lazy-rules placeholder="密码" v-model="creatUpdateQuery.re_pwd"
                  standout bg-color="white" bottom-slots :rules="rulesArr[3]">
                  <template v-slot:append>
                    <q-icon :name="isPwd2 ? 'visibility_off' : 'visibility'" class="cursor-pointer" @click="showPwd2" />
                  </template>
                </q-input>
              </div>
            </li>
            <li class="gap_wrepper">
              <div>角色</div>
              <div>
                <q-select dense outlined emit-value multiple options-dense v-model="rolesChecked"
                  :options="rolesOption" />
              </div>
            </li>
          </ul>
        </q-form>
      </q-card-section>
      <!-- 对话框的底部 -->
      <q-card-actions align="right">
        <q-btn unelevated label="取消" type="reset" style="color: #686868;" outline @click="closeEbitUpdate" />
        <q-btn outline label="确定" type="submit" color="primary"
          @click="dialogStatus === 'create' ? handlerCreateSensor() : handlerUpdateSensor()" />
      </q-card-actions>
    </q-card>
  </q-dialog>

  <q-dialog v-model="dialogPassVisible" persistent @mousedown="dialogDrag($event, 1)" @mousemove="dragIcon($event)">
    <q-card>
      <!-- 对话框的头部 -->
      <q-card-section class="row items-center q-pb-none">
        <div class="text-h6">修改密码</div>
        <q-space />
        <q-btn icon="close" flat round dense @click="dialogPassVisible = false"></q-btn>
      </q-card-section>
      <!-- 对话框的主体-->
      <q-card-section class="q-pt-none">
        <q-form ref="rulePassForm" class="q-pa-lg dialog-form-container">
          <ul>
            <li>
              <div>
                <span style="color: red">*</span>
                旧密码
              </div>
              <div>
                <q-input dense outlined :type="loginPass" lazy-rules placeholder="密码" v-model="ruleForm.pwd" standout
                  bg-color="white" bottom-slots :rules="rulesArr[4]">
                  <template v-slot:append>
                    <q-icon :name="isPwd ? 'visibility_off' : 'visibility'" class="cursor-pointer" @click="showPwd" />
                  </template>
                </q-input>
              </div>
            </li>
            <li>
              <div>
                <span style="color: red">*</span>
                新密码
              </div>
              <div>
                <q-input dense outlined :type="loginPass2" lazy-rules placeholder="密码" v-model="ruleForm.new_pwd"
                  standout bg-color="white" bottom-slots :rules="rulesArr[5]">
                  <template v-slot:append>
                    <q-icon :name="isPwd2 ? 'visibility_off' : 'visibility'" class="cursor-pointer" @click="showPwd2" />
                  </template>
                </q-input>
              </div>
            </li>
            <li>
              <div>
                <span style="color: red">*</span>
                重复新密码
              </div>
              <div>
                <q-input outlined dense placeholder="密码" v-model="ruleForm.re_new_pwd" :rules="rulesArr[6]"
                  :type="moreisPwd ? 'password' : 'text'">
                  <template v-slot:append>
                    <q-icon :name="moreisPwd ? 'visibility_off' : 'visibility'" class="cursor-pointer"
                      @click="moreisPwd = !moreisPwd" />
                  </template>
                </q-input>
                <!-- <q-input outlined v-model="ruleForm.re_new_pwd" dense :rules="rulesArr[6]" /> -->
              </div>
            </li>
          </ul>
        </q-form>
      </q-card-section>
      <!-- 对话框的底部 -->
      <q-card-actions align="right">
        <q-btn unelevated label="取消" type="reset" style="color: #686868;" outline @click="dialogPassVisible = false" />
        <q-btn outline label="确定" color="primary" @click="handlerodifyPass" />
      </q-card-actions>
    </q-card>
  </q-dialog>

  <!-- 删除 提示框 -->
  <DeleteDialog :isShowDelete="isShowDelete" :tipInfo="tipInfo" @closeDeleteDialog="closeDeleteDialog"
    @confirmDelete="confirmDelete" />
</template>
<script>
import { ref } from 'vue'
import { fetchOwnerInfo, createOwnerInfo, updateOwnerInfo, deleteOwnerInfo, modifyPass, resetPasswords } from 'src/api/personAdmini'
import { gainRolesList } from 'src/api/permission'
import DeleteDialog from 'src/components/deleteDialog/index'
import Pagination from 'src/components/pagination'
import { mapGetters } from 'vuex';
import DeleteBtn from 'src/components/btnCom/deleteBtn'
import EditBtn from 'src/components/btnCom/editBtn'
import drag from 'src/components/mixins/drag.js'

export default {
  mixins: [drag],
  components: {
    DeleteDialog,
    Pagination,
    DeleteBtn,
    EditBtn
  },
  data() {
    return {
      moreisPwd: ref(true),
      dataList: [],
      searchShow: false,
      isPwd: true,
      loginPass: 'password',
      isPwd2: true,
      loginPass2: 'password',
      filter: ref(''),
      columns: [
        { name: 'idIndex', required: true, label: 'ID', align: 'center', field: 'idIndex', isSort: true },
        { name: 'username', required: true, label: '用户名', align: 'center', field: 'username' },
        { name: 'telephone', required: true, label: '电话', align: 'center', field: 'telephone' },
        { name: 'email', align: 'center', label: '邮箱', field: 'email' },
        { name: 'roles', align: 'center', label: '角色', field: 'roles' }
      ],
      // 表格头部
      headerSeach: ref(''),
      seachContent: {
        '用户名': 'username',
        '电话': 'telephone',
        '邮箱': 'email'
      },
      selectSeach: [
        '', '用户名', '电话', '邮箱'
      ],
      // 右侧表头选择
      visibleColumns: ref(['idIndex', 'username', 'telephone', 'email', 'roles']),
      // 对话框
      isAddOrUpdate: false,
      changeFormTitle: '增加人员',
      rulesArr: [
        [val => val && val.length > 0 || '请输入用户名'],
        [val => val && val.length > 0 || '请输入电话'],
        [val => val && val.length > 0 || '请输入密码'],
        [val => val && val.length > 0 || '请输入确认密码'],
        [val => val && val.length > 0 || '请输入旧密码'],
        [val => val && val.length > 0 || '请输入新密码'],
        [val => val && val.length > 0 || '请重复新密码'],
      ], // 表单验证
      creatUpdateQuery: {
        username: '',
        telephone: '',
        email: '',
        password: '',
        re_pwd: ''
      },
      rolesChecked: [],
      rolesOption: [],
      ruleForm: {
        pwd: '',
        new_pwd: '',
        re_new_pwd: ''
      },
      pagination: { // 分页
        sortBy: 'desc', // 列名
        descending: false, // 是否按照降序排序
        page: 1, // 页码（当前显示第几页的数据）
        rowsPerPage: 10, // 每页多少行
        rowsNumber: 10 // 共多少条
      },
      queryList: {
        page: 1,
        page_size: 10,
        ordering: 'id'
      },
      loading: false, // 表格的加载状态
      seneorParams: {
        category: [],
        model: [],
        vendor: [],
        modelName: []
      },
      sensorAllType: {
        query_param: 'one'
      },
      isShowDelete: false,
      tipInfo: '',
      dialogPassVisible: false,
      detailList: [],
      dialogStatus: 'create',
      textMap: {
        create: '添加人员信息',
        update: '修改人员信息',
      },
      czRow: null,
    }
  },
  computed: {
    ...mapGetters(['themeColor'])
  },
  watch: {
  },
  created() {
    this.getList()
    this.getRolesList()
  },
  methods: {
    // 刷新
    handlerRefresh() {
      this.handleResetSearch()
    },
    updatePage(val) {
      if (!val) return
      this.pagination.page = val * 1
      this.getList()
    },
    // 切换每页的行数
    updateSizes(val) {
      this.pagination.rowsPerPage = parseFloat(val)
      this.getList()
    },
    /**
     * 搜索
     */
    handlerSearch() {
      this.pagination.page = 1
      this.getList()
    },
    /**
     * 复位搜索
     */
    handleResetSearch() {
      this.pagination = {
        sortBy: 'desc',
        descending: false,
        page: 1,
        rowsPerPage: 10
      }
      this.queryList = {
        page: 1,
        page_size: 10,
        ordering: 'id'
      }
      this.headerSeach = ''
      this.getList()
    },
    // 是否显示密码
    showPwd() {
      this.isPwd = !this.isPwd
      if (this.isPwd) {
        this.loginPass = 'password'
      } else {
        this.loginPass = ''
      }
    },
    showPwd2() {
      this.isPwd2 = !this.isPwd2
      if (this.isPwd2) {
        this.loginPass2 = 'password'
      } else {
        this.loginPass2 = ''
      }
    },
    /**
     * 排序
     */
    handlerSort() {
      this.pagination.descending = !this.pagination.descending
      this.getList()
    },
    getList() {
      this.listLoading = true
      this.queryList.page = this.pagination.page
      this.queryList.page_size = this.pagination.rowsPerPage
      this.queryList.ordering = this.pagination.descending ? '-id' : 'id'

      let listQu = Object.assign({}, this.queryList)
      fetchOwnerInfo(listQu).then(res => {
        this.dataList = []
        const { status, data, totalCounts } = res
        if (data && data.length > 0) {
          data.forEach((item, index) => {
            // 处理序号
            if (!this.pagination.descending) {
              item.idIndex = index + 1 + (this.queryList.page - 1) * this.queryList.page_size
            } else {
              item.idIndex = totalCounts - index - (this.queryList.page - 1) * this.queryList.page_size
            }
            this.dataList.push({
              uid: item.uid,
              idIndex: item.idIndex,
              username: item.username,
              telephone: item.telephone,
              email: item.email,
              roles: item.roles.join(',')
            })
          })
        }
        this.pagination.rowsNumber = totalCounts
        this.listLoading = false
      }).catch(error => {
        this.listLoading = false
        console.log(error)
      })
    },

    resetTemp() {
      this.creatUpdateQuery = {
        username: '',
        telephone: '',
        email: '',
        password: '',
        re_pwd: '',
        roles: null,
      }
      this.rolesChecked = null
    },
    handlerAddSensor() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.isAddOrUpdate = true
      this.isShowPwd = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetValidation()
      })
    },
    handlerCreateSensor() {
      this.$refs['dataForm'].validate().then(success => {
        if (success) {
          const assignQuery = Object.assign({}, this.creatUpdateQuery)
          assignQuery.roles = this.rolesChecked
          createOwnerInfo(assignQuery).then(res => {
            if (res.status === 200) {
              this.isAddOrUpdate = false
              this.getList()
              this.$q.notify({
                type: 'positive',
                position: 'top',
                message: `添加成功！`
              })
            }
          })
        }
      })
    },
    searchShowClick() {
      this.searchShow = !this.searchShow
    },
    // 编辑
    handlerEbitSensor(row) {
      const { uid, username, telephone, email, roles } = row
      this.oldUsername = username
      this.creatUpdateQuery = {
        uid,
        username,
        telephone,
        email
      }
      if (roles && roles.length > 0) {
        this.rolesChecked = roles.split(',')
      } else {
        this.rolesChecked = null
      }
      this.rulesArr[2] = []
      this.rulesArr[3] = []
      this.dialogStatus = 'update'
      this.isAddOrUpdate = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetValidation()
      })
    },
    handlerUpdateSensor() {
      this.$refs['dataForm'].validate().then(valid => {
        if (valid) {
          const tempData = {}
          tempData.email = this.creatUpdateQuery.email
          tempData.telephone = this.creatUpdateQuery.telephone
          tempData.username = this.creatUpdateQuery.username
          tempData.roles = this.rolesChecked

          updateOwnerInfo(tempData, this.creatUpdateQuery.uid).then(res => {
            this.isAddOrUpdate = false
            if (localStorage.getItem('username_GFYW') === this.oldUsername && localStorage.getItem('username_GFYW') !== tempData.username) {
              this.$store.dispatch('login/logoutFun')
              this.$store.commit('app/SET_VISITED_VIEWS') //  清空可见tab标签
              this.$router.push({
                path: '/login',
                query: {
                  change_username: 'true'
                }
              })
            } else {
              this.getList()
            }
            this.$q.notify({
              type: 'positive',
              position: 'top',
              message: `更新成功！`
            })
          })
        }
      })
    },
    /**
    * 关闭 添加/编辑 弹出对话框
    */
    closeEbitUpdate() {
      this.resetTemp()
      this.isAddOrUpdate = false
    },
    /**
     * 打开是否删除提示框
     */
    handlerDeleteSensor(val) {
      this.isShowDelete = true
      this.tipInfo = '确定是否删除该人员?'
      if (val) this.deleteId = val.uid
    },
    /**
     * 确定删除
     */
    confirmDelete() {
      if (this.tipInfo == '确定是否删除该人员?') {
        if (!this.deleteId) {
          this.$q.notify({
            type: 'warning',
            position: 'top',
            message: '设备ID不存在！'
          })
          return
        }
        deleteOwnerInfo(this.deleteId).then(res => {
          const { status, msg } = res
          if (status === 200) {
            this.isShowDelete = false
            if (this.pagination.page > 1 && this.pagination.rowsNumber % this.pagination.rowsPerPage === 1) {
              this.pagination.page -= 1
            }
            this.getList()
            this.$q.notify({
              type: 'positive',
              position: 'top',
              message: `删除成功！`
            })
          } else {
            this.$q.notify({
              type: 'positive',
              position: 'top',
              message: msg
            })
          }
        })
      } else {
        // 管理员重置密码 未开发
        let data = {
          uid: this.czRow.uid
        }
        resetPasswords(data).then(res => {
          const { status, msg } = res
          if (status == 200) {
            this.$q.notify({
              type: 'positive',
              position: 'top',
              message: msg
            })
          } else {
            this.$q.notify({
              type: 'positive',
              position: 'top',
              message: msg
            })
          }
          this.isShowDelete = false
        })
      }

    },
    /**
     * 关闭删除提示框
     */
    closeDeleteDialog() {
      this.isShowDelete = false
    },
    resetRuleForm() {
      this.ruleForm = {
        pwd: '',
        new_pwd: '',
        re_new_pwd: ''
      }
    },
    // 修改密码
    handleModify(row) {
      this.isShowDelete = true
      this.tipInfo = '确定是否进行重置?'
      this.czRow = row
      this.ruleForm.uid = this.czRow.uid
      // this.dialogPassVisible = true
      // this.resetRuleForm()
      // this.ruleForm.uid = this.czRow.uid
      // this.$nextTick(() => {
      //   this.$refs['rulePassForm'].resetValidation()
      // })
    },
    handlerodifyPass() {
      this.$refs['rulePassForm'].validate().then(valid => {
        if (valid) {
          modifyPass(this.ruleForm).then(res => {
            if (res.status === 200) {
              this.dialogPassVisible = false
              this.$q.notify({
                type: 'positive',
                position: 'top',
                message: `修改密码成功！`
              })
            }
          })
        }
      })
    },
    /**
     * 获取角色
     */
    getRolesList() {
      gainRolesList().then(res => {
        const { status, data } = res
        if (status === 200) {
          if (data && data.length > 0) {
            data.forEach(item => {
              item.value = item.name
              item.label = item.name
            })
          }
          this.rolesOption = data
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
// 弹出的对话框样式
.dialog-form-container {
  ul {
    li {
      overflow: hidden;
      min-height: 42px;
      line-height: 42px;
      margin-bottom: 5px;

      >div {
        &:first-child {
          float: left;
          margin-right: 10px;
        }

        &:last-child {
          float: right;
          width: 200px;
        }
      }

      >span {
        &:first-child {
          float: left;
          margin-right: 10px;
        }

        &:last-child {
          float: right;
          width: 200px;
        }
      }
    }
  }
}

.gap_wrepper {
  margin-bottom: 22px !important;
}
</style>
